<?php

namespace App\Admin\Controllers;

use App\Admin\Extensions\Tools\SynTask;
use App\Handlers\RedisHandler;
use App\Models\RateType;
use App\Models\Task;

use Encore\Admin\Form;
use Encore\Admin\Grid;
use Encore\Admin\Facades\Admin;
use Encore\Admin\Layout\Content;
use App\Http\Controllers\Controller;
use Encore\Admin\Controllers\ModelForm;
use Encore\Admin\Widgets\Table;
use Illuminate\Foundation\Auth\User;
use Illuminate\Support\Facades\Input;

class TaskController extends Controller
{
    use ModelForm;

    /**
     * Index interface.
     *
     * @return Content
     */
    public function index()
    {
        return Admin::content(function (Content $content) {

            $content->header('微信任务调度');
            $content->description('系统每5分钟自动同步数据，如需立即同步，请点击 同步数据');
            $content->row(view('admin.lineChart'));
            $content->body($this->grid());
        });
    }

    /**
     * Edit interface.
     *
     * @param $id
     * @return Content
     */
    public function edit($id)
    {
        return Admin::content(function (Content $content) use ($id) {

            $content->header('微信任务调度');
            $content->description('');

            $content->body($this->form('edit')->edit($id));
        });
    }

    /**
     * Create interface.
     *
     * @return Content
     */
    public function create()
    {
        return Admin::content(function (Content $content) {

            $content->header('微信任务调度');
            $content->description('');

            $content->body($this->form());
        });
    }

    /**
     * Make a grid builder.
     *
     * @return Grid
     */
    protected function grid()
    {
        return Admin::grid(Task::class, function (Grid $grid) {

            if (!request()->get('_sort')) $grid->model()->orderByDesc('id');
            $grid->id('ID')->sortable();
            $grid->column('task_title','任务名');
            $grid->column('article_title','文章名');
            $grid->column('status','状态')->sortable()->display(function ($value){
                $statusColor = config('system.task.status_color')[$value];
                return "<span class=\"label label-$statusColor\">".config('system.task.status')[$value]."</span>";
            });
            $grid->column('urls','网址');
            $grid->column('duration','间隔时间');
            $grid->column('valid_read_amount','增加/当前/目标阅读')->sortable()->display(function ($value){
                return "{$this->valid_read_amount}/{$this->current_read_amount}/{$this->target_read_amount}";
            });
            $grid->column('valid_like_amount','增加/当前/目标点赞')->sortable()->display(function ($value){
                return "{$this->valid_like_amount}/{$this->current_like_amount}/{$this->target_like_amount}";
            });
            $grid->column('date','预约日期')->sortable();
            $grid->column('rateType.title','速度曲线');
            $grid->column('rateType.data','曲线模型')->display(function($value){
                $data = json_decode($value);
                if($data) $value = implode(',',$data);
                return <<<EOF
              <span class="lineChartRender">$value</span>
EOF;
            });
            $grid->column('enable','启用')->switch(config('system.switch.states'))->sortable();
            $grid->created_at('创建时间')->sortable();
            $grid->filter(function (Grid\Filter $filter){
                $filter->like('task_title','任务名');
                $filter->like('article_title','文章名');
                $filter->like('urls','网址');
                $filter->equal("duration","间隔时间");
                $filter->equal('rate_type_id','曲线')->select(function (){
                    return RateType::where('enable',1)->get()->pluck('title','id');
                });
                $filter->equal('enable','启用')->select([1=>'启用',2=>'禁用']);
                $filter->equal('status','状态')->select(config('system.task.status'));
                $filter->between('target_read_amount','目标阅读数');
                $filter->between('target_like_amount','目标点赞数');
                $filter->between('valid_read_amount','有效阅读数');
                $filter->between('valid_like_amount','有效点赞数');
                $filter->between('date','预约日期')->date();
                $filter->between('created_at','创建时间')->date();
            });

            $grid->tools(function ($tools){
                $tools->append(new SynTask());
            });
        });
    }

    /**
     * Make a form builder.
     *
     * @return Form
     */
    protected function form($mode='create')
    {
        return Admin::form(Task::class, function (Form $form) use($mode) {
            $form->display('id', 'ID');
            $form->text('task_title','任务名');
            $form->number('target_read_amount','目标阅读数')->default(5000)->rules('integer|required');
            $form->number('target_like_amount','目标点赞数')->default(0)->rules('integer|required');
            $form->number('duration','任务间隔时间(秒)')->default(60)->rules('integer|required');
            $form->date('date', '预约日期')->default(date('Y-m-d'));
            $form->select('status','状态')->options(config('system.task.status'))->default(TASK_STATUS_PENDING);
            $form->switch('enable', '启用')->default(1)->states(config('system.switch.states'));
            if($mode=='edit'){
                $form->text('urls','文章地址')->help('一行一个，批量添加')->rules('required');
            }else $form->textarea('urls','文章地址列表')->help('一行一个，批量添加')->rules('required');
            $form->select('rate_type_id','速率曲线')->options(function (){
                return RateType::where('enable',1)->get()->pluck('title','id');
            })->default(1)
            ->help("<a target='_blank' href='".route('rate-type')."'>管理速率曲线</a>");
            $form->display('created_at', '创建时间');
            $form->hidden('user_id');
            $form->saving(function (Form $form) {
                $form->user_id = Admin::user()->id;
            });
        });
    }

    public function store()
    {
        if(request('id')){
            return $this->form()->store();
        }
        $urls = explode("\n",request('urls'));
        $data = request()->all();
        $data = collect($data);
        if($data->has('enable')){
            if($data->get('enable')=='on') $data->put('enable',1);
            else $data->put('enable',2);
        }
        $data->put('user_id',Admin::user()->id);
        $fields = ['task_title','target_read_amount','target_like_amount','date','status','enable','rate_type_id','user_id'];
        if(!empty($urls)){
            foreach ($urls as $url){
                $task = new Task();
                $task->urls = $url;
                foreach ($fields as $field){
                    $task->$field = $data->get($field);
                }
                $task->save();
            }
        }


        admin_toastr(trans('admin.save_succeeded'));

        $url = Input::get(Form\Builder::PREVIOUS_URL_KEY) ?: $this->form()->resource(0);

        return redirect($url);
        //return $this->form()->store();
    }


    public function sync()
    {
        RedisHandler::syncTasks();
        return ['status_code' => 200, 'message' => '同步成功'];
    }

    public function clear()
    {
        RedisHandler::clearTaskDeviceLog();
        return ['status_code' => 200, 'message' => '清空成功'];
    }


}
